<?php
$page_title = '展示报名意愿信息 - 考务管理系统';
require 'common/header.php';
checkLogin();
requireRole($conn, '考试项目管理员');

// 获取考试项目ID
$exam_id = intval($_GET['exam_id'] ?? 0);
if ($exam_id <= 0) {
    header('Location: exam_projects.php');
    exit();
}

// 获取考试项目信息
$exam_sql = "SELECT * FROM exams WHERE id = ?";
$exam_stmt = $conn->prepare($exam_sql);
$exam_stmt->bind_param('i', $exam_id);
$exam_stmt->execute();
$exam_result = $exam_stmt->get_result();

if ($exam_result->num_rows === 0) {
    header('Location: exam_projects.php');
    exit();
}

$exam = $exam_result->fetch_assoc();

// 检查项目是否已发布报名
if ($exam['project_progress'] < 3) {
    header('Location: signup_management.php?exam_id=' . $exam_id);
    exit();
}

// 获取排序参数
$sort_field = $_GET['sort'] ?? 'signup_time';
$sort_order = $_GET['order'] ?? 'asc';

// 验证排序字段
$allowed_sorts = ['user_name', 'signup_intention', 'signup_time'];
if (!in_array($sort_field, $allowed_sorts)) {
    $sort_field = 'signup_time';
}

// 验证排序方向
if (!in_array($sort_order, ['asc', 'desc'])) {
    $sort_order = 'asc';
}

// 构建排序SQL
$order_sql = '';
switch ($sort_field) {
    case 'user_name':
        $order_sql = "ORDER BY sl.user_name {$sort_order}";
        break;
    case 'signup_intention':
        $order_sql = "ORDER BY sl.signup_intention {$sort_order}";
        break;
    case 'signup_time':
    default:
        $order_sql = "ORDER BY sl.signup_time {$sort_order}";
        break;
}

// 获取报名意愿数据
$intentions_sql = "SELECT sl.*, s.position, s.dept_id, s.service_years, s.responsibility
                   FROM signups_leaves sl
                   LEFT JOIN staff s ON sl.user_id = s.user_id
                   WHERE sl.exam_id = ?
                   {$order_sql}";
$intentions_stmt = $conn->prepare($intentions_sql);
$intentions_stmt->bind_param('i', $exam_id);
$intentions_stmt->execute();
$intentions_result = $intentions_stmt->get_result();

// 获取统计信息
$stats_sql = "SELECT
                COUNT(*) as total_signups,
                SUM(CASE WHEN signup_intention = 1 THEN 1 ELSE 0 END) as accept_count,
                SUM(CASE WHEN signup_intention = 0 THEN 1 ELSE 0 END) as reject_count
              FROM signups_leaves
              WHERE exam_id = ?";
$stats_stmt = $conn->prepare($stats_sql);
$stats_stmt->bind_param('i', $exam_id);
$stats_stmt->execute();
$stats_result = $stats_stmt->get_result();
$stats = $stats_result->fetch_assoc();

// 生成下一个排序状态的函数
function getNextSortState($current_field, $current_order, $field) {
    if ($current_field !== $field) {
        return ['sort' => $field, 'order' => 'asc'];
    }

    switch ($current_order) {
        case 'asc':
            return ['sort' => $field, 'order' => 'desc'];
        case 'desc':
            return ['sort' => '', 'order' => ''];
        default:
            return ['sort' => $field, 'order' => 'asc'];
    }
}

// 生成排序箭头
function getSortArrow($current_field, $current_order, $field) {
    if ($current_field !== $field) {
        return '<span class="sort-arrow">↕️</span>';
    }

    switch ($current_order) {
        case 'asc':
            return '<span class="sort-arrow active">↑</span>';
        case 'desc':
            return '<span class="sort-arrow active">↓</span>';
        default:
            return '<span class="sort-arrow">↕️</span>';
    }
}
?>

<div class="page-header">
    <h1 class="page-title">报名意愿信息</h1>
    <p class="page-description">考试项目"<?php echo htmlspecialchars($exam['exam_name']); ?>"的监考意愿统计</p>
</div>

<!-- 项目信息和统计 -->
<div class="card">
    <div class="card-header">
        <h3 class="card-title">报名统计概览</h3>
        <div class="action-buttons">
            <a href="signup_management.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-secondary">返回报名管理</a>
        </div>
    </div>
    <div class="card-content">
        <div class="stats-overview">
            <div class="stat-item">
                <div class="stat-value"><?php echo $stats['total_signups']; ?></div>
                <div class="stat-label">总报名人数</div>
            </div>
            <div class="stat-item accept">
                <div class="stat-value"><?php echo $stats['accept_count']; ?></div>
                <div class="stat-label">希望参加</div>
            </div>
            <div class="stat-item reject">
                <div class="stat-value"><?php echo $stats['reject_count']; ?></div>
                <div class="stat-label">拒绝参加</div>
            </div>
            <div class="stat-item">
                <div class="stat-value">
                    <?php
                    $participation_rate = $stats['total_signups'] > 0 ?
                        round(($stats['accept_count'] / $stats['total_signups']) * 100, 1) : 0;
                    echo $participation_rate . '%';
                    ?>
                </div>
                <div class="stat-label">参与率</div>
            </div>
        </div>
    </div>
</div>

<!-- 报名意愿详细列表 -->
<div class="card">
    <div class="card-header">
        <h3 class="card-title">详细报名意愿列表</h3>
        <div class="sort-info">
            <span>点击表头进行排序（三态循环：升序→降序→无排序）</span>
        </div>
    </div>

    <div class="card-content">
        <?php if ($intentions_result->num_rows > 0): ?>
            <div class="table-container">
                <table class="intentions-table">
                    <thead>
                        <tr>
                            <th>序号</th>
                            <th class="sortable" onclick="sortTable('user_name')">
                                监考员姓名
                                <?php echo getSortArrow($sort_field, $sort_order, 'user_name'); ?>
                            </th>
                            <th>职位</th>
                            <th>工作年限</th>
                            <th>责任心等级</th>
                            <th class="sortable" onclick="sortTable('signup_intention')">
                                监考意愿
                                <?php echo getSortArrow($sort_field, $sort_order, 'signup_intention'); ?>
                            </th>
                            <th class="sortable" onclick="sortTable('signup_time')">
                                填报时间
                                <?php echo getSortArrow($sort_field, $sort_order, 'signup_time'); ?>
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $row_number = 1;
                        while($intention = $intentions_result->fetch_assoc()):
                        ?>
                            <tr class="intention-row <?php echo $intention['signup_intention'] ? 'accept-row' : 'reject-row'; ?>">
                                <td><?php echo $row_number++; ?></td>
                                <td>
                                    <div class="user-info">
                                        <div class="user-name"><?php echo htmlspecialchars($intention['user_name']); ?></div>
                                        <div class="user-id">ID: <?php echo htmlspecialchars($intention['user_id']); ?></div>
                                    </div>
                                </td>
                                <td><?php echo htmlspecialchars($intention['position'] ?: '未知'); ?></td>
                                <td><?php echo $intention['service_years'] ? $intention['service_years'] . '年' : '未知'; ?></td>
                                <td>
                                    <div class="responsibility-level">
                                        <?php
                                        $responsibility = $intention['responsibility'] ?: 5;
                                        echo $responsibility . '/10';
                                        ?>
                                        <div class="level-bar">
                                            <div class="level-fill" style="width: <?php echo ($responsibility * 10); ?>%;"></div>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <span class="intention-badge <?php echo $intention['signup_intention'] ? 'accept' : 'reject'; ?>">
                                        <?php echo $intention['signup_intention'] ? '希望参加' : '拒绝参加'; ?>
                                    </span>
                                </td>
                                <td class="signup-time">
                                    <?php echo date('Y-m-d H:i:s', strtotime($intention['signup_time'])); ?>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="empty-state">
                <div class="empty-icon">📝</div>
                <h3>暂无报名记录</h3>
                <p>还没有监考员填报意愿</p>
                <p class="empty-help">请等待监考员填报或检查报名是否已正确发布</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- 导出功能 -->
<?php if ($intentions_result->num_rows > 0): ?>
<div class="card">
    <div class="card-header">
        <h3 class="card-title">数据导出</h3>
    </div>
    <div class="card-content">
        <div class="export-options">
            <button onclick="exportToCSV()" class="btn btn-info">导出CSV</button>
            <button onclick="printTable()" class="btn btn-secondary">打印表格</button>
            <button onclick="copyToClipboard()" class="btn btn-secondary">复制数据</button>
        </div>
    </div>
</div>
<?php endif; ?>

<style>
/* 报名意愿页面样式 */
.stats-overview {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 20px;
}

.stat-item {
    text-align: center;
    padding: 20px;
    border-radius: 8px;
    border: 1px solid var(--border-color);
    background: white;
}

.stat-item.accept {
    border-left: 4px solid var(--success-green);
}

.stat-item.reject {
    border-left: 4px solid var(--error-red);
}

.stat-value {
    font-size: 28px;
    font-weight: 600;
    color: var(--primary-blue);
    margin-bottom: 8px;
}

.stat-label {
    color: var(--text-secondary);
    font-size: 14px;
}

.sort-info {
    font-size: 12px;
    color: var(--text-secondary);
}

.intentions-table {
    width: 100%;
    border-collapse: collapse;
}

.intentions-table th,
.intentions-table td {
    padding: 12px 8px;
    text-align: left;
    border-bottom: 1px solid var(--border-color);
}

.intentions-table th {
    background-color: var(--background-light);
    font-weight: 600;
    position: sticky;
    top: 0;
    z-index: 10;
}

.sortable {
    cursor: pointer;
    user-select: none;
    transition: background-color 0.2s ease;
}

.sortable:hover {
    background-color: rgba(22, 119, 255, 0.1);
}

.sort-arrow {
    margin-left: 5px;
    font-size: 12px;
}

.sort-arrow.active {
    color: var(--primary-blue);
}

.intention-row {
    transition: background-color 0.2s ease;
}

.intention-row:hover {
    background-color: rgba(22, 119, 255, 0.05);
}

.accept-row {
    border-left: 3px solid var(--success-green);
}

.reject-row {
    border-left: 3px solid var(--error-red);
}

.user-info {
    display: flex;
    flex-direction: column;
}

.user-name {
    font-weight: 600;
    color: var(--text-primary);
}

.user-id {
    font-size: 12px;
    color: var(--text-secondary);
}

.responsibility-level {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.level-bar {
    width: 50px;
    height: 4px;
    background-color: #e5e7eb;
    border-radius: 2px;
    overflow: hidden;
    margin-top: 4px;
}

.level-fill {
    height: 100%;
    background-color: var(--primary-blue);
    transition: width 0.3s ease;
}

.intention-badge {
    padding: 4px 12px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 500;
    display: inline-block;
}

.intention-badge.accept {
    background-color: rgba(34, 197, 94, 0.1);
    color: var(--success-green);
}

.intention-badge.reject {
    background-color: rgba(239, 68, 68, 0.1);
    color: var(--error-red);
}

.signup-time {
    font-size: 12px;
    color: var(--text-secondary);
}

.empty-state {
    text-align: center;
    padding: 60px 20px;
    color: var(--text-secondary);
}

.empty-icon {
    font-size: 48px;
    margin-bottom: 20px;
}

.empty-state h3 {
    color: var(--text-primary);
    margin-bottom: 10px;
}

.empty-state p {
    margin-bottom: 8px;
}

.empty-help {
    color: var(--text-secondary);
    font-size: 14px;
}

.export-options {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .stats-overview {
        grid-template-columns: repeat(2, 1fr);
    }

    .intentions-table {
        font-size: 12px;
    }

    .intentions-table th,
    .intentions-table td {
        padding: 8px 4px;
    }

    .export-options {
        flex-direction: column;
    }
}

@media (max-width: 480px) {
    .stats-overview {
        grid-template-columns: 1fr;
    }
}
</style>

<script>
// 排序功能
function sortTable(field) {
    const currentSort = '<?php echo $sort_field; ?>';
    const currentOrder = '<?php echo $sort_order; ?>';

    let nextSort, nextOrder;

    if (currentSort !== field) {
        nextSort = field;
        nextOrder = 'asc';
    } else {
        switch (currentOrder) {
            case 'asc':
                nextSort = field;
                nextOrder = 'desc';
                break;
            case 'desc':
                nextSort = '';
                nextOrder = '';
                break;
            default:
                nextSort = field;
                nextOrder = 'asc';
        }
    }

    const url = new URL(window.location);
    if (nextSort) {
        url.searchParams.set('sort', nextSort);
        url.searchParams.set('order', nextOrder);
    } else {
        url.searchParams.delete('sort');
        url.searchParams.delete('order');
    }

    window.location.href = url.toString();
}

// 导出CSV功能
function exportToCSV() {
    const table = document.querySelector('.intentions-table');
    const rows = table.querySelectorAll('tr');

    let csv = [];

    // 添加表头
    const headers = [];
    rows[0].querySelectorAll('th').forEach(th => {
        headers.push('"' + th.textContent.trim().replace(/"/g, '""') + '"');
    });
    csv.push(headers.join(','));

    // 添加数据行
    for (let i = 1; i < rows.length; i++) {
        const row = [];
        rows[i].querySelectorAll('td').forEach(td => {
            row.push('"' + td.textContent.trim().replace(/"/g, '""') + '"');
        });
        csv.push(row.join(','));
    }

    // 下载CSV
    const csvContent = csv.join('\n');
    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = '<?php echo htmlspecialchars($exam['exam_name']); ?>_报名意愿.csv';
    link.click();
}

// 打印表格
function printTable() {
    const printWindow = window.open('', '_blank');
    const table = document.querySelector('.intentions-table').outerHTML;
    const examName = '<?php echo htmlspecialchars($exam['exam_name']); ?>';

    printWindow.document.write(`
        <html>
        <head>
            <title>${examName} - 报名意愿信息</title>
            <style>
                body { font-family: Arial, sans-serif; margin: 20px; }
                h1 { color: #1677ff; }
                table { width: 100%; border-collapse: collapse; margin-top: 20px; }
                th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                th { background-color: #f5f5f5; }
                .accept { color: #52c41a; }
                .reject { color: #ff4d4f; }
            </style>
        </head>
        <body>
            <h1>${examName} - 报名意愿信息</h1>
            <p>打印时间：${new Date().toLocaleString()}</p>
            ${table}
        </body>
        </html>
    `);

    printWindow.document.close();
    printWindow.print();
}

// 复制到剪贴板
function copyToClipboard() {
    const table = document.querySelector('.intentions-table');
    const rows = table.querySelectorAll('tr');

    let text = [];

    rows.forEach(row => {
        const rowData = [];
        row.querySelectorAll('th, td').forEach(cell => {
            rowData.push(cell.textContent.trim());
        });
        text.push(rowData.join('\t'));
    });

    navigator.clipboard.writeText(text.join('\n')).then(() => {
        alert('数据已复制到剪贴板');
    }).catch(err => {
        console.error('复制失败:', err);
        alert('复制失败，请手动选择表格内容');
    });
}

// 表格行动画效果
document.addEventListener('DOMContentLoaded', function() {
    const rows = document.querySelectorAll('.intention-row');

    rows.forEach((row, index) => {
        row.style.opacity = '0';
        row.style.transform = 'translateY(20px)';

        setTimeout(() => {
            row.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
            row.style.opacity = '1';
            row.style.transform = 'translateY(0)';
        }, index * 50);
    });
});
</script>

<?php
// 关闭数据库连接
if (isset($conn)) {
    $conn->close();
}

require 'common/footer.php';
?>